<?php

namespace app\admin\controller\stock;

use app\common\controller\Backend;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use app\admin\model\UserDepart;
use app\admin\model\User;
use fast\Tree;
use think\Config;
use think\exception\PDOException;

/**
 * 股权证管理
 *
 * @icon fa fa-circle-o
 */
class Stock extends Backend
{

    /**
     * Stock模型对象
     * @var \app\admin\model\Stock
     */
    protected $model = null;
	protected $noNeedRight = ['users', 'dotransfer', 'doflow', 'depart'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Stock;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			$map = [];
			$groupIds = $this->auth->getGroupIds();
			if($groupIds[0] == 3)
			{
				$map['stock.depart_id'] = $this->auth->depart_id;
			}
			
            $list = $this->model
                    ->with(['user'])
					->where($where)
					->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as &$row) {
                $depart = UserDepart::get($row['depart_id']);
				$row['depart_id'] = $depart['name'];
				if($row['sub_depart'])
				{
					$sub_depart = UserDepart::get($row['sub_depart']);
					$row['depart_id'] .= '/'.$sub_depart['name'];
				}
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

	public function users()
	{
		//设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('username,nickname');

			$map = [];
			if($this->request->get('id'))
			{
				$map['id'] = ['<>', $this->request->get('id')];
			}
			else
			{
				$groupIds = $this->auth->getGroupIds();
				if($groupIds[0] == 3)
				{
					$map['depart_id'] = $this->auth->depart_id;
				}
			}
			
            $list = model('User')
				->with('depart')
                ->where($where)
				->where($map)
                ->where('id', '<>', 1)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
		
		$this->assignconfig("id", $this->request->get('uid'));
		return $this->view->fetch();
	}
	
	public function reissue($ids = null)
	{
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        $result = false;
        Db::startTrans();
        try {
			$data = array(
				'uid' => $row['uid'],
				'idcode' => $params['newidcode'],
				'depart_id' => $row['depart_id'],
				'sub_depart' => $row['sub_depart'],
				'uname' => $row['uname'],
				'money' => $row['money'],
				'lmoney' => $row['lmoney'],
				'releasetime' => time(),
				'status' => 1
			);
			$this->model->allowField(true)->save($data);
			
			$result = $row->delete();
            Db::commit();
        } catch (Exception $e) {
			Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('补办失败'));
        }
        $this->success('补办成功');
	}
	
	public function transferUser($ids = null)
	{
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
		$from_user = model('User')->get($row['uid']);
		$to_user = model('User')->get($params['uid']);
		if($params['money']>$row['money'])
		{
			$this->error('转让金额不能大于本金');
		}
        $result = false;
        Db::startTrans();
        try {
			$data = array(
				'sid' => $row['id'],
				'idcode' => $row['idcode'],
				'money' => $params['money'],
				'from_uid' => $from_user['id'],
				'from_username' => $from_user['username'],
				'from_nickname' => $from_user['nickname'],
				'from_depart' => $from_user['depart_id'],
				'to_uid' => $to_user['id'],
				'to_username' => $to_user['username'],
				'to_nickname' => $to_user['nickname'],
				'to_depart' => $to_user['depart_id']
			);
			model('StockTransfer')->allowField(true)->save($data);
			
			$row->status = 2;
			$result = $row->save();
            Db::commit();
        } catch (Exception $e) {
			Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('转让失败'));
        }
        $this->success('转让成功，等待审核');
	}
	
	public function flow($ids = null)
	{
		//设置过滤方法		
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
			$row = $this->model->get($ids);
			if (!$row) {
				$this->error(__('No Results were found'));
			}
		
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('name');

			$list = model('UserDepart')
                ->where($where)
				->where('id', '<>', $row['depart_id'])
				->where('pid', 0)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
		
		$this->assignconfig("ids", $ids);
		return $this->view->fetch();
	}
	
	public function doFlow()
	{
		if ($this->request->isPost()) {
			$id = $this->request->post("id");
			$row = $this->model->get($id);
			if (!$row) {
				$this->error(__('No Results were found'));
			}
			
			$to_id = $this->request->post("to_id");
            if ($to_id) {
                $result = false;
				Db::startTrans();
                try {
					$from_user = model('User')->get($row['uid']);
					$data = array(
						'sid' => $row['id'],
						'idcode' => $row['idcode'],
						'money' => $row['money'],
						'from_uid' => $from_user['id'],
						'from_username' => $from_user['username'],
						'from_nickname' => $from_user['nickname'],
						'from_depart' => $from_user['depart_id'],
						'to_depart' => $to_id,
					);
                    model('StockFlow')->allowField(true)->save($data);
					
					$row->status = 3;
					$result = $row->save();
					Db::commit();
                } catch (Exception $e) {
					Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('转出成功，等待审核');
                } else {
                    $this->error(__('转出失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
		}
	}
	
	/* public function transferUser($ids = null)
	{
		//设置过滤方法		
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
			$row = $this->model->get($ids);
			if (!$row) {
				$this->error(__('No Results were found'));
			}
		
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('username,nickname');

            $list = model('User')
				->with('depart')
                ->where($where)
                ->where('id', '<>', $row['uid'])
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
		$this->assignconfig("ids", $ids);
		return $this->view->fetch();
	}
	
	public function doTransfer()
	{
		if ($this->request->isPost()) {
			$id = $this->request->post("id");
			$row = $this->model->get($id);
			if (!$row) {
				$this->error(__('No Results were found'));
			}
			
			$to_uid = $this->request->post("to_uid");
            if ($to_uid) {
                $result = false;
				Db::startTrans();
                try {
					$from_user = model('User')->get($row['uid']);
					$to_user = model('User')->get($to_uid);
					$data = array(
						'sid' => $row['id'],
						'idcode' => $row['idcode'],
						'money' => $row['money'],
						'from_uid' => $from_user['id'],
						'from_username' => $from_user['username'],
						'from_nickname' => $from_user['nickname'],
						'from_depart' => $from_user['depart_id'],
						'to_uid' => $to_uid,
						'to_username' => $to_user['username'],
						'to_nickname' => $to_user['nickname'],
						'to_depart' => $to_user['depart_id']
					);
                    model('StockTransfer')->allowField(true)->save($data);
					
					$row->status = 2;
					$result = $row->save();
					Db::commit();
                } catch (Exception $e) {
					Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('转让成功');
                } else {
                    $this->error(__('转让失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
		}
	} */
	
	public function depart()
	{
		$groupList = collection(UserDepart::column('id,pid,name'))->toArray();

        Tree::instance()->init($groupList);
        $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		
        $groupName = [];
        foreach ($groupList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
		
		echo json_encode($groupName);
		exit;
	}
	
	public function newlist()
	{
		//当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			$map['stock.status'] = 0;
            $list = $this->model
                    ->with(['user'])
					->where($where)
					->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as &$row) {
                $depart = UserDepart::get($row['depart_id']);
				$row['depart_id'] = $depart['name'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
	}
	
	public function review($ids = "")
	{
		$ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $list = $this->model->where('id', 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
					$v->status = 1;
                    $count += $v->save();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
	}
	
	public function census()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
			
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			
			$groupIds = $this->auth->getGroupIds();
			if($groupIds[0] == 3)
			{
				$map['depart_id'] = $this->auth->depart_id;
				
				$list = $this->model
					->field('sub_depart as depart, sum(money) as summoney')
					->group('sub_depart')
					->where($where)
					->where($map)
                    ->select();
			}
			else
			{
				$list = $this->model
					->field('depart_id as depart, sum(money) as summoney')
					->group('depart_id')
					->where($where)
                    ->select();
			}

			$site = Config::get("site");
            foreach ($list as $key=>$row) {
				$list[$key]['id'] = $key+1;
                $depart = UserDepart::get($row['depart']);
				$list[$key]['depart'] = $depart['name'];
				$list[$key]['ratemoney'] = round($row['summoney']*$site['rate'], 2);
            }

            $result = array("total" => count($list), "rows" => $list, "rate" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function import()
    {
    	$file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
				
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, "'" . str_replace(["'", ","], ["''", "','"], $line) . "'\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : trim($val, "'");
                }
				
				$row = [];
				foreach($values as $k => $v)
				{
					if($k == 1)
					{
						if(empty($v)) break;
						$row['idcode'] = $v;
					}
					if($k == 2) $row['uname'] = $v;
					if($k == 3) 
					{
						$inseruser = array(
							'depart_id' => $this->auth->depart_id,
							'username' => $v,
							'nickname' => $values[2],
							'idcard' => $values[5]
						);
						
						$subDepart = $values[4];
						$subDepart = model('userDepart')->get(['name'=>$subDepart, 'pid'=>$this->auth->depart_id]);
						if($subDepart)
						{
							$inseruser['sub_depart'] = $subDepart['id'];
						}
						else
						{
							$inseruser['sub_depart'] = 0;
						}
							
						$user = model('user')->get(['username'=>$v]);
						if($user)
						{
							$user->save($inseruser);
							
							$row['uid'] = $user['id'];
							$row['depart_id'] = $user['depart_id'];
							$row['sub_depart'] = $user['sub_depart'];
						}
						else
						{
							$salt = \fast\Random::alnum();
							$inseruser['password'] = \app\common\library\Auth::instance()->getEncryptPassword('123456', $salt);
							$inseruser['salt'] = $salt;
							$inseruser['joinip'] = '127.0.0.1';
							$inseruser['jointime'] = time();
							$inseruser['status'] = 'normal';
							$user = User::create($inseruser);

							$row['uid'] = $user['id'];
							$row['depart_id'] = $user['depart_id'];
							$row['sub_depart'] = $user['sub_depart'];
						}
					}
					
					if($k == 6) $row['money'] = $v;
					if($k == 7) $row['lmoney'] = $v;
					if($k == 8)
					{
						if($v)
						{
							$row['releasetime'] = strtotime($v);
						}
						else
						{
							$row['releasetime'] = time();
						}
					}
				}
				
                if ($row) {
					$row['status'] = 1;
					
					$stock = $this->model->get(['idcode'=>$row['idcode']]);
					if($stock)
					{
						$stock->save($row);
					}
					else
					{
						$insert[] = $row;
					}
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if ($insert) {
			try {
				$this->model->saveAll($insert);
			} catch (PDOException $exception) {
				$msg = $exception->getMessage();
				if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
					$msg = "导入失败，包含【{$matches[1]}】的记录已存在";
				};
				$this->error($msg);
			} catch (Exception $e) {
				$this->error($e->getMessage());
			}
		}

        $this->success();
    }
}
